package com.kujie.ai.config;

import io.modelcontextprotocol.client.McpAsyncClient;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.mcp.AsyncMcpToolCallbackProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.List;

/**
 * 客户端 配置
 *
 * @author check
 * @date 2025-07-24
 */
@Configuration
public class ChatClientConfig {
    @Autowired
    private ChatMemoryRepository chatMemoryRepository;


    @Bean
    @Primary
    public AsyncMcpToolCallbackProvider buildAsyncMcpToolCallbackProvider(List<McpAsyncClient> clients) {
        return AsyncMcpToolCallbackProvider.builder().mcpClients(clients).build();
    }

    @Bean
    public ChatClient buildChatClient(ChatClient.Builder openAiChatModel,
                                      AsyncMcpToolCallbackProvider tools,
                                      ChatMemory chatMemory) {

        // 清除上下文记忆
        List<String> conversationIds = chatMemoryRepository.findConversationIds();
        for (String conversationId : conversationIds) {
            chatMemoryRepository.deleteByConversationId(conversationId);
        }

        return openAiChatModel
                .defaultToolCallbacks(tools.getToolCallbacks())
//                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build(),
//                        PromptChatMemoryAdvisor.builder(chatMemory).build())
                .build();
    }
}
